const User = require('../model/user.model')

class UserService {
  async createUser (user) {
    const res = await User.create(user)
    return res.dataValues
  }

  async getUserInfo (user) {
    const {
      id,
      username,
      password,
      email
    } = user
    const whereOpt = {}
    id && Object.assign(whereOpt, { id })
    username && Object.assign(whereOpt, { username })
    password && Object.assign(whereOpt, { password })
    email && Object.assign(whereOpt, { email })

    const res = await User.findOne({
      attributes: [
        'id',
        'username',
        'password',
        'email',
        'email_verified_at'
      ],
      where: whereOpt
    })

    return res ? res.dataValues : null
  }

  async updateById (user) {
    const { id, username, password, email } = user
    const whereOpt = { id }
    const newUser = {}

    username && Object.assign(newUser, { username })
    password && Object.assign(newUser, { password })
    email && Object.assign(newUser, { email })

    const res = await User.update(newUser, {
      where: whereOpt
    })

    return res[0] > 0
  }
}

module.exports = new UserService()
